package com.study.leetcode;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Solution_890 {
    public static List<String> findAndReplacePattern(String[] words, String pattern) {
        List<String> matched = new LinkedList<>();
        for (String word : words) {
            if (word.length() == pattern.length() && isMapped(word, pattern)) {
                matched.add(word);
            }
        }
        return matched;
    }

    public static boolean isMapped(String word, String pattern) {
        Map<String, String> map = new HashMap<>(word.length());
        for (int i = 0; i < word.length(); i++) {
            char w = word.charAt(i);
            char p = pattern.charAt(i);

            String s = map.get(String.valueOf(p));
            if (s != null) {
                if (s.charAt(0) != w) {
                    return false;
                }
            } else {
                map.put(String.valueOf(p), String.valueOf(w));
            }
            int count = 0;
            for (Map.Entry<String, String> entry : map.entrySet()) {
                if (entry.getValue().charAt(0) == w) {
                    count++;
                }
                if (count > 1) {
                    return false;
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        String[] words = {"abc", "deq", "mee", "aqq", "dkd", "ccc"};
        String pattern = "abb";
        List<String> stringList = findAndReplacePattern(words, pattern);
        System.out.println("stringList = " + stringList);
    }
}
